package com.domain.ex;

import com.domain.HttpResponse;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by Administrator on 2015/12/30 0030.
 * 继承springMVC的异常处理接口
 * 将spring拦截的级别为debug的错误打印出来
 * 自定义异常输出
 */
public class WebExceptionResolver implements HandlerExceptionResolver {

    private static final Logger LOG = LoggerFactory.getLogger(WebExceptionResolver.class);

    @Autowired
    private Gson gson;


    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        if (e instanceof BizException){
            LOG.warn("业务类异常：",e);
            BizException ex = (BizException) e;
            try {
                HttpResponse httpResponse = HttpResponse.create(ex.getCodes(),ex.getBizMsg());
                httpServletResponse.getWriter().write(gson.toJson(httpResponse));
            } catch (IOException e1) {
                LOG.warn("IOException：",e1);
            }
        }else {
            LOG.warn("非业务类异常：",e);
            try {
                HttpResponse httpResponse = HttpResponse.create(Codes.SystemError);
                httpServletResponse.getWriter().write(gson.toJson(httpResponse));
            } catch (IOException e1) {
                LOG.warn("IOException：", e1);
            }
        }
        return new ModelAndView();
    }
}
